import types from './types'
import { ipcRenderer } from 'electron'
import { checkWindowNofify } from './helpers'
import {
  fetchNotifications,
  setNoticeRead,
  getUserMessages,
  setUserMessageRead
} from '@/api'

const getType = (originalType) => {
  let type = 'atme'
  if (originalType === 'user_message') {
    type = 'userMessage'
  } else if (originalType === 'event') {
    type = 'event'
  }
  return type
}

export default {
  async fetchNotifications ({ commit }, params = {}) {
    const type = getType(params.type)
    commit(types.SET_NOTICE_LOADING, { type, value: true })
    const data = await fetchNotifications(params)
    commit(types.SET_NOTIFICATIONS, {
      type,
      data: { current_page: params.page || 1, loading: false, ...data }
    })
  },

  async setNoticeRead ({ commit }, { id, type }) {
    await setNoticeRead(id)
    commit(types.SET_NOTICE_READ, { id, type })
  },

  async setUserMessageRead ({ commit }, { id }) {
    await setUserMessageRead(id)
    commit(types.SET_USER_MESSAGE_READ, { id })
  },

  async fetchUserMessages ({ commit }, params = {}) {
    commit(types.SET_NOTICE_LOADING, { type: 'userMessage', value: true })
    const data = await getUserMessages(params)
    commit(types.SET_NOTIFICATIONS, {
      type: 'userMessage',
      data: {
        current_page: params.page || 1,
        loading: false,
        ...data
      }
    })
  },

  async setFirstPageData ({ commit }, datas) {
    Object.keys(datas).forEach(type => {
      commit(types.SET_FIRST_PAGE, {
        type,
        data: datas[type]
      })
    })
  },

  async fetchNewDataByDiff ({ dispatch, rootState, state }, datas = {}) {
    Object.keys(datas).forEach(type => {
      const filtered = state[`${type}Filtered`]
      // 若某 tab 通知有更新，且当前正在该 tab 下，且在第一页，则拉取新数据
      if (
        type === rootState.currentTab &&
        state.notifications[type].current_page === 1 &&
        datas[type].length
      ) {
        if (type === 'userMessage') {
          dispatch('fetchUserMessages')
        } else {
          dispatch('fetchNotifications', {
            unread: filtered === 'unread',
            participating: filtered === 'participating'
          })
        }
      }
    })
  },

  async fetchUserMessageFirstPage ({ dispatch }) {
    const data = await getUserMessages({ unread: true })
    dispatch('setFirstPageData', {
      'userMessage': data
    })
  },

  // 首次获取数据
  async fetchAllFirstPage ({ dispatch, commit }) {
    let [refererData, eventData, userMessageData] = await Promise.all([
      fetchNotifications({ type: 'referer' }),
      fetchNotifications({ type: 'event' }),
      getUserMessages()
    ])
    dispatch('setFirstPageData', {
      'atme': refererData,
      'event': eventData,
      'userMessage': userMessageData
    })
  },

  async notifyNewNotification ({ state, dispatch, commit }) {
    let [refererData, eventData, userMessageData] = await Promise.all([
      fetchNotifications({ type: 'referer' }),
      fetchNotifications({ type: 'event' }),
      getUserMessages()
    ])

    dispatch('fetchNewDataByDiff', {
      'atme': refererData,
      'event': eventData,
      'userMessage': userMessageData
    })
    dispatch('setFirstPageData', {
      'atme': refererData,
      'event': eventData,
      'userMessage': userMessageData
    })
    checkWindowNofify(state, 'atme', refererData)
    checkWindowNofify(state, 'event', eventData)
    checkWindowNofify(state, 'userMessage', userMessageData)
  },

  setEventFiltered ({ commit }, value) {
    commit(types.SET_EVENT_FILTERED, value)
  },

  setAtMeFiltered ({ commit }, value) {
    commit(types.SET_AT_ME_FILTERED, value)
  },

  toggleWindowNotifyStatus ({ state, commit }) {
    commit(types.NOTIFY_STATUE_TOGGLE)
    ipcRenderer.send('set-tray-icon', state.notifyStatus ? 'notify' : 'no-notify')
  },

  setFetchApiInterval ({ state, dispatch, commit }) {
    clearInterval(state.pollingTimer)
    const timer = setInterval(() => {
      dispatch('notifyNewNotification')
    }, state.fetchApiTimes)
    commit(types.SET_INTERVAL_FETCH_API, timer)
  },

  setSettingForm ({ state, commit, dispatch }, data) {
    commit(types.SET_SETTING_FORM, data)
    dispatch('setFetchApiInterval')
  },
  clearPollInterval ({ state }) {
    clearInterval(state.pollingTimer)
  }
}
